package cn.seaboot.admin.rabbit.test;


import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author Mr.css
 * @version 2020-11-12 19:31
 */
public class ExchangeReceive {
    private static final String QUEUE_NAME = "queue_name";

    public static void main(String[] args) {
        try {
            Connection connection = ConnectionUtil.getConnection();
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            // 限制消息接收的数量
             channel.basicQos(0,1,false);

            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                           byte[] body) {
                    //查看消息主体内容
                    String message = new String(body, StandardCharsets.UTF_8);
                    System.out.println("[receive]：" + message);




                    // 手动 ACK 消息
                    try {
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };

            // 设置为自动 ACK
            channel.basicConsume(QUEUE_NAME, false, consumer);
        } catch (IOException | ShutdownSignalException | ConsumerCancelledException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}

